/**
 * Created by XianTao on 2016/4/25
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.wechat.portal.service;

import lombok.extern.slf4j.Slf4j;
import org.lego.util.HttpUtil;
import org.lego.wechat.base.entity.WxCorp;
import org.lego.wechat.base.msg.InMsgParser;
import org.lego.wechat.base.msg.in.InMsg;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 微信消息接收器，负责接收微信服务器推送过来的消息
 */
@Service
@Slf4j
public class WechatReceiver {
    /**
     * 将微信服务器推送的消息，解密后返回
     *
     * @param wxCorp  微信号
     * @param request HttpServletRequest
     * @return 消息实体类
     */
    public InMsg getInMsg(WxCorp wxCorp, HttpServletRequest request) {
        String inMsgXml = (String) request.getSession().getAttribute("wechat_message");
        if (ObjectUtils.isEmpty(inMsgXml)) {
            inMsgXml = HttpUtil.readIncommingRequestData(request);
        }
        log.info("接收消息: \n{}", inMsgXml);
        return InMsgParser.parser(inMsgXml, wxCorp.getAgentId());
    }
}
